package com.lyl.goods.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class AuthInterceptor implements HandlerInterceptor {
    /**
     * @Description: 登录拦截器
     * @Author: Liyunlong
     * @Date: 2024/3/1
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取HttpSession
        HttpSession session = request.getSession();
        // 检查session中是否存在已登录用户信息
        String currentUser = (String) session.getAttribute("currentUser");

        if (currentUser != null) {
            // 已登录，允许访问
            return true;
        } else {
            // 未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
    }
}